package com.example.demo.coder;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MessageDecoder {

    public static MessageObject decoder(String msg){
        if (msg != null && !"".equals(msg)){
            Pattern pattern = Pattern.compile("^\\[(.*)\\](\\s-\\s(.*))?");
            Matcher matcher = pattern.matcher(msg);
            MessageObject messageObject = new MessageObject();
            if (matcher.find()){
                String headers = matcher.group(1);
                String content = matcher.group(3);
                String[] split = headers.split("\\]\\[");
                String cmd = split[0];
                long time = Long.parseLong(split[1]);
                String nickName = split[2];
                messageObject.setCmd(cmd);
                messageObject.setContent(content);
                messageObject.setNickName(nickName);
                messageObject.setTime(time);
                return messageObject;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    //将MessageObject对象编码为字符串指令
    public static String encoder(MessageObject msg){
        if(msg == null){return null;}
        String message = "["+msg.getCmd()+"]["+msg.getTime()+"]";
        if(msg.getCmd().equals(MessageStatus.SYSTEM)){
            message += "["+msg.getOnlineNum()+"]";
        }else if(msg.getCmd().equals(MessageStatus.CHAT)
                ||msg.getCmd().equals(MessageStatus.LOGIN)
                ||msg.getCmd().equals(MessageStatus.LOGOUT)){
            message += "["+msg.getNickName()+"]";
            message += "["+msg.getOnlineNum()+"]";
        }
        if(msg.getContent() != null && !msg.getContent().equals("")){
            message += " - "+msg.getContent();
        }
        return message;
    }
}
